Skip to content

feat(agent)!: reject requests that arrive before initialize - #162

Merged
ThomasK33 merged 5 commits into
mainfrom
acp-tck/init-gate
Nov 24, 2026
Merged

ThomasK33 merged 5 commits into
mainfrom
acp-tck/init-gate

Conversation

@ThomasK33

Copy link
Copy Markdown
Member

Why

A run of the ACP Test Compatibility Kit (acp-tck v0.5.0) against example/agent found two gaps in the SDK. AgentSideConnection passes requests to the Agent before initialize, where the spec says an agent SHOULD answer them with -32600. And errors.go has no constructor for -32002 (Resource not found), the code the spec gives an unknown session. The TCK gate that checks both is the next PR in this stack.

What changed

  • NewResourceNotFound (-32002). A test pins every New* constructor to the schema's ErrorCode code and title, and fails when the schema gains a code that has no constructor.
  • Breaking: until the Agent's Initialize returns without an error, AgentSideConnection answers every other request, _ extension requests included, with -32600 and drops every notification. A failed initialize leaves the connection uninitialized. $/cancel_request is still handled by the read loop.
  • NewConnection starts reading before it returns, so a handler could read a.conn before NewAgentSideConnection stored it. This race is on main too, in registerPrompt. Handlers now wait on a ready channel, as the proxy's handleWhenReady does.
  • example/agent sends agentInfo, answers an unknown session with -32002 and data.sessionId, and rejects an unissued session/list cursor and an unknown mode with -32602.
  • Docs: a new MIGRATION_v0.21.md section, plus the README and doc.go. The G3 session-delete journey expects -32002. The verify-session-cancel fingerprint is re-synced.

Scope

The agent side only. ClientSideConnection and the proxy do not change. The tests that used to skip initialize now send it first, and none of them lost an assertion.

Tradeoffs

  • The gate checks the flag when a handler starts, not when a message arrives. So a client that sends session/new without waiting for the initialize reply can get -32600. Every client in this repo waits.
  • I fixed the race in agent.go instead of splitting connection.go. Splitting would shift the line citations of both TLA+ gates. fix: start reading only after the side connection stores conn #84 is an open PR that takes the connection.go route.

Blast Radius

Agents built on the SDK whose clients send messages before initialize completes.

Verification

  • make test, and go test -race -count=3 . and ./example/....
  • Each new test fails without its change. The race test fails under -race without the ready wait.
  • All 16 G3 journeys pass. verify-session-cancel passes 7/7 and verify-notification-barrier 10/10.
  • The TCK against example/agent: ACP-ERROR-003, ACP-ERROR-004, ACP-ERROR-005, ACP-INIT-004 and ACP-LIST-003 go from FAIL to PASS, and nothing else changes.
  • Two independent verifiers reviewed the branch. Every finding is fixed.

Generated with xum • Model: anthropic:claude-opus-5-5 • Thinking: high

The spec gives -32002 (Resource not found) to a request that names a session or file that does not exist, with data.sessionId for an unknown session. errors.go had a constructor for every other ErrorCode in the schema. A test now pins each constructor to the schema's ErrorCode code and title, and fails when the schema gains a code without one.

_Generated with [`xum`](https://github.com/coder/xum) • Model: `anthropic:claude-opus-5-5` • Thinking: `high`_
The spec says an agent SHOULD answer a request other than initialize that arrives before initialization completes with -32600. AgentSideConnection passed every request and notification to the Agent. Until the Agent's Initialize returns without an error, it now answers every other request, _ extension requests included, with -32600 and drops every notification. A failed initialize leaves the connection uninitialized.

NewConnection starts reading before it returns, so a handler could read a.conn before NewAgentSideConnection stored it (registerPrompt on main does too). Handlers now wait on a ready channel that the constructor closes once a.conn is set, as the proxy's handleWhenReady does.

Tests that skipped initialize now send it first. MIGRATION_v0.21.md, the README and doc.go describe the gate, and the verify-session-cancel fingerprint is re-synced.

BREAKING CHANGE: AgentSideConnection answers a request other than initialize with -32600, and drops a notification, until the Agent's Initialize returns without an error.

_Generated with [`xum`](https://github.com/coder/xum) • Model: `anthropic:claude-opus-5-5` • Thinking: `high`_
The example agent now returns agentInfo, answers a session it does not know (prompt, set_mode, set_config_option, load) with NewResourceNotFound and data.sessionId, and rejects a session/list cursor it never issued and an unknown mode with -32602. The G3 session-delete journey and its feature doc expect -32002 for a prompt on a deleted session.

_Generated with [`xum`](https://github.com/coder/xum) • Model: `anthropic:claude-opus-5-5` • Thinking: `high`_
@ThomasK33

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 23, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-23T15:47:39.476833Z 23fb821 Manual request
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 89409f3ad7

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread agent.go Outdated
Comment on lines +71 to +72
if err == nil {
a.initialized.Store(true)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Mark initialized only after encoding the success response

When Initialize returns a response containing an unencodable value, such as malformed json.RawMessage in InitializeResponse.Meta, a.handle reports no error so this flag becomes true, but Connection.handleInbound subsequently fails to marshal the response and sends the client -32603. The client therefore observes a failed initialization while subsequent requests such as session/new pass the gate and reach the agent; keep the connection uninitialized until the successful response has at least been encoded.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 3a1481c: the gate now encodes the initialize response itself and stays closed when encoding fails, so the client's -32603 and the gate agree. TestAgentSideConnection_InitializeThatDoesNotEncodeKeepsTheGate covers it, and fails without the fix.

An Initialize response that json.Marshal rejects, such as a Meta value holding invalid raw JSON, reaches the client as -32603, but the gate opened anyway, so later requests reached the Agent after an initialize the client saw fail. The gate now encodes the response itself and stays closed when that fails.

_Generated with [`xum`](https://github.com/coder/xum) • Model: `anthropic:claude-opus-5-5` • Thinking: `high`_
@ThomasK33

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 3a1481c045

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread extensions.go Outdated
Comment on lines +39 to +40
if !a.initialized.Load() {
return a.handleBeforeInitialize(ctx, method, params)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Reject messages that arrived before initialization

When input is buffered or handlers are delayed by scheduling, the concurrent initialize handler can set initialized before an earlier request or notification reaches this load, so that earlier message bypasses the gate and reaches the agent. This is reproducible with the added TestAgentSideConnection_HandlesMessagesWaitingAtConstruction under go test -race -count=10, where the session/cancel preceding initialize is delivered; enforce the gate using message arrival order rather than the flag's value when the handler happens to run.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 23fb821: the connection records the arrival number of the initialize that opened it, and a message passes the gate only if it arrived after that one. TestAgentSideConnection_GateKeysOnArrivalOrder runs handlers out of arrival order and fails with the flag-only gate.

…alize

Request handlers run concurrently, so an initialize could finish before the handler of a message that arrived ahead of it checked the gate, and that message reached the Agent. The connection now records the arrival number of the initialize that opened it, and a message passes the gate only if it arrived after that one. The verify-session-cancel fingerprint is re-synced.

_Generated with [`xum`](https://github.com/coder/xum) • Model: `anthropic:claude-opus-5-5` • Thinking: `high`_
@ThomasK33

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 23fb821372

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread agent.go
Comment on lines +74 to +75
at := a.openedAt.Load()
return at != 0 && a.arrivalOf(ctx) >= at

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Keep pipelined messages behind initialization completion

When a client writes initialize and another request back-to-back, the second message can arrive while Initialize is still running but have its handler scheduled only after openedAt is set. This comparison then admits it because its arrival number is greater than the initialize request's, even though it arrived before initialization completed, so it reaches the Agent instead of receiving the documented -32600. Track whether each message arrived after successful completion rather than only after the initialize request's arrival.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not changing this one. The gate holds back every message that arrived before the initialize that opened the connection. A message pipelined after initialize can still get through when its handler starts after initialize returned. The docs say so: a client sends other requests only after the initialize reply, and no client here pipelines. Rejecting by completion time would need the arrival count at the moment initialize finishes. Only the read loop touches that counter, so it would take a new atomic in connection.go and a remap of the notification-barrier skill's line citations, all for a SHOULD.

@ThomasK33

Copy link
Copy Markdown
Member Author

Pre-merge verification of 23fb821: PASS+NOTES

I ran these checks on a detached worktree of 23fb821 against base 04d1252:

  • make test: pass. go test -race -count=3 .: pass (512 s). go test -race ./example/...: pass.
  • G3 (acp-verify): doctor ok and all 16 journeys PASS, proxy included. In session-delete, prompt A fails gives -32002 Resource not found, and the order check prints exactly the line in the feature file.
  • TLA: verify-session-cancel/check.sh exits 0 (7/7 configs, fingerprint matches). verify-notification-barrier/check.sh exits 0.
  • TCK v0.5.0 against example/agent: ACP-ERROR-003, -004, -005, ACP-INIT-004 and ACP-LIST-003 go from FAIL to PASS. The other 129 rows are unchanged, and the only FAIL left is ACP-SESSION-004, as on base. The -race build gives the same results.
  • Scratch gate test: one buffered write of 20-80 pre-initialize messages (session/new, prompt, list, _ requests and notifications, session/cancel, invalid initialize), then initialize and pipelined requests, 500 rounds x -cpu 1,2,4,8. No pre-initialize message reached the Agent, and every pre-initialize request got an error. Control: with opened() ignoring arrival order, the test fails at round 5 (-cpu 1).
  • Docs: every sentence in the README agent-side text, MIGRATION "Requests before initialize", doc.go, the agent.go comments and the session-cancel scope note matches the code. No client in example/ pipelines (each waits on ClientSideConnection.Initialize), and every G3 journey sends initialize first and waits for its reply. The NewResourceNotFound snippet compiles. No test lost an assertion: two got stricter (-32603 checked, replyTo(1)).
  • treefmt --fail-on-change (gofmt, mdformat, actionlint, zizmor): 0 changed. PR CI is green.

Notes (none blocks the merge):

  1. The -race TCK run at head wrote 3 race logs, all in example/agent. main.go:843 calls SetAgentConnection after NewAgentSideConnection returns, and the handler reads that field in sessionUpdate at main.go:380 with nothing ordering the two. Base has the same race (main.go:817 against :354; 6 of 60 driven base runs). Base also has an SDK race on asc.conn (agent.go:106), which this PR's ready channel removes. Nothing in the SDK gate showed up in any race log.
  2. The docs say the gate opens once Initialize "returns without an error" (agent.go:47, doc.go:7, README.md:63, README.md:305, MIGRATION_v0.21.md:375). The code also requires the response to encode (agent.go:96). An Initialize that returns nil with a response that cannot be encoded sends -32603 to the client and keeps the gate closed. The client sees that as a failed initialize, which the docs do cover.
  3. When two initializes succeed concurrently, the first one to finish opens the gate (agent.go:101). A message that arrived between them can get -32600. Only a client that sends two initializes at once can hit this.

Generated with xum • Model: anthropic:claude-opus-5-5 • Thinking: high

@ThomasK33
ThomasK33 added this pull request to the merge queue Nov 24, 2026
Merged via the queue into main with commit e47104f Nov 24, 2026
5 checks passed
@ThomasK33
ThomasK33 deleted the acp-tck/init-gate branch November 24, 2026 13:06
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants